package cn.gdchent.nativehotfix.andfix.act

import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import android.widget.TextView
import android.widget.Toast
import cn.gdchent.nativehotfix.R
import cn.gdchent.nativehotfix.andfix.manager.AndFixPatchManager
import java.io.File


class AndFixActivity : AppCompatActivity(), View.OnClickListener {

    private val MY_PERMISSIONS_REQUEST_READ_CONTACTS=0
    private val FILE_END: String = ".apatch"
    private lateinit var mPatchDir: String
    private val TAG: String = "AndFix"
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fix)
        val tvCreateBug = this.findViewById<TextView>(R.id.tv_create_bug)
        val tvFixBug = this.findViewById<TextView>(R.id.tv_fix_bug)
        tvCreateBug.setOnClickListener(this)
        tvFixBug.setOnClickListener(this)

        mPatchDir = externalCacheDir.absolutePath + "/apatch/"
        System.out.println(mPatchDir)
        //是为了创建我们的文件夹
        val file = File(mPatchDir)
        file.let {
            if (!it.exists()) {
                it.mkdirs()
            }
            Log.i(TAG, "路径:".plus(it.absoluteFile))
        }
    }


    //按钮点击事件１
    private fun createBug() {
        //执行一个ｂｕg
        Log.i(TAG, "bugBefore")
        val res="我是bug1"
        //val res = "我是修复后的bug";
        Toast.makeText(this, res, Toast.LENGTH_SHORT).show()
        Log.i(TAG, res)
    }

    //按钮点击事件１
    private fun fixBug() {
        AndFixPatchManager.getInstance()?.addPatch(getPatchFilePathName())
    }

    //构造patch文件名
    private fun getPatchFilePathName(): String {
        return mPatchDir.plus("imooc").plus(FILE_END)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_create_bug -> {
                createBug()
            }
            R.id.tv_fix_bug -> {
                fixBug()
            }
        }
    }

    private fun showWaringDialog() {
        val dialog: AlertDialog = AlertDialog.Builder(this)
            .setTitle("警告！")
            .setMessage("请前往设置->应用->PermissionDemo->权限中打开相关权限，否则功能无法正常运行！")
            .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which ->
                // 一般情况下如果用户不授权的话，功能是无法运行的，做退出处理
                finish()
            }).show()
    }
}
